#include "funcs_timer.h"
#include "myunistd.h"
// Timing vars for benchmarking.
uint32 time_init = 0;

// Frame delta vars.
uint32 currTime = 0;
uint32 prevTime;
uint32 prevFpsUpdate = 0;

// Updated with a certain frequency.
float fps = 0;

// The frequency by which to update the FPS.
float fpsUpdateFrequency = 1;

// Frames since last FPS update.
int frames = 0;

// The current timestep.
float dt = 0;
void timer_open()
{
	time_init = SDL_GetTicks();	
}
void step()
{
	// Frames rendered
	frames++;
		
	// "Current" time is previous time by now.
	prevTime = currTime;

	// Get ticks from SDL
	currTime = SDL_GetTicks();

	// Convert to number of seconds
	dt = (currTime - prevTime)/1000.0f;

	// Update FPS?
	if((currTime - prevFpsUpdate)/1000.0f > fpsUpdateFrequency)
	{
		fps = frames/fpsUpdateFrequency;
		prevFpsUpdate = currTime;
		frames = 0;
	}

	if(dt < 0)
		printf("Timer: WTF: %f: \n", dt);
}

float getDelta()
{
	return dt;
}

float getFPS()
{
	return fps;
}

void sleep(int ms)
{		
	SDL_Delay((unsigned int)ms);
}

float getTime()
{
	return (SDL_GetTicks() - time_init)/1000.0f;
}

int l_getFPS(lua_State *L){
    int fps = getFPS();
    lua_pushinteger(L, fps);
	return 1;
}

int l_getDelta(lua_State *L){
	int fps = getDelta();
	lua_pushinteger(L, fps);
	return 1;
}
